package com.cti.commons.mqtt.acpect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;

import com.cti.commons.mqtt.repository.MqttReceiveMessageLog;
import com.cti.commons.mqtt.repository.MqttReceiveMessageRepository;
import com.cti.commons.mqtt.thread.MessageContext;

import lombok.extern.slf4j.Slf4j;

@Aspect
@Slf4j
public class ConsumerTransactionAspect {

    @Autowired
    private MqttReceiveMessageRepository messageRepository;

    @Pointcut("@annotation(com.cti.commons.mqtt.annotation.MqttTransaction)")
    public void mqttTransactionPointcut() {
    }

    @Around(value = "mqttTransactionPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        MqttReceiveMessageLog receiveMessageLog = MessageContext.getReceiveMessageLog();
        result = joinPoint.proceed();
        if (null != receiveMessageLog) {
            receiveMessageLog.success();
            messageRepository.save(receiveMessageLog);
        }
        return result;
    }

}
